package com.dbq.fast.business.setting;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;

import com.dbq.fast.common.net.RemoteApiCallBack;
import com.dbq.fast.util.SpUtil;
import com.yiba.logutils.utils.FileUtil;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import okhttp3.ResponseBody;

public class DownloadService extends Service {

    private DownloadServiceBinder mBinder = new DownloadServiceBinder();

    public DownloadService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        return mBinder;
    }

    public class DownloadServiceBinder extends Binder {
        DownloadService getService() {
            return DownloadService.this;
        }
    }

    static ExecutorService executorService = Executors.newFixedThreadPool(1);

    public void downloadApk(String apkName, String url, OnDownloadStatusListener listener) {
        setOnDownloadStatusListener(listener);
        executorService.execute(() -> {
            downloadApk(apkName, url);
        });
    }


    public OnDownloadStatusListener downloadStatusListener;

    public void setOnDownloadStatusListener(OnDownloadStatusListener downloadStatusListener) {
        this.downloadStatusListener = downloadStatusListener;
    }

    public interface OnDownloadStatusListener {
        void start();


        void downloadError();

        void writeLocaling();

        void writePercent(long fileSizeDownloaded, long total);

        void writeLocalError();

        void complete();

    }

    private static boolean isDownloading = false;

    private void downloadApk(String apkName, String apkUrl) {

        if (downloadStatusListener != null) {
            downloadStatusListener.start();
        }
        SettingApi.downloadApk(apkUrl, new RemoteApiCallBack<ResponseBody>() {

            @Override
            public void onSuccess(ResponseBody requestBody) {

                new Thread(() -> {
                    writeResponseBodyToDisk(apkName, requestBody);
                }).start();
            }

            @Override
            public void onFail(int status, String message) {
                if (downloadStatusListener != null) {
                    downloadStatusListener.downloadError();
                }
            }
        });

    }


    private synchronized boolean writeResponseBodyToDisk(String apkName, ResponseBody body) {
        if (isDownloading) return false;
        isDownloading = true;
        try {
            // todo change the file location/name according to your needs
            File futureStudioIconFile = new File(FileUtil.getTempDirPath(this) + "/" + apkName);

            if (futureStudioIconFile.exists()) {
                futureStudioIconFile.delete();
            } else {
                futureStudioIconFile.createNewFile();
            }
            InputStream inputStream = null;
            OutputStream outputStream = null;
            if (downloadStatusListener != null) {
                downloadStatusListener.writeLocaling();
            }
            try {
                byte[] fileReader = new byte[1024 * 20];//开的这块内存不能太大

                long fileSize = body.contentLength();
                long fileSizeDownloaded = 0;

                inputStream = body.byteStream();
                outputStream = new FileOutputStream(futureStudioIconFile);

                while (true) {
                    int read = inputStream.read(fileReader);
                    if (read == -1) {
                        break;
                    }
                    outputStream.write(fileReader, 0, read);
                    fileSizeDownloaded += read;
                    if (downloadStatusListener != null) {
                        downloadStatusListener.writePercent(fileSizeDownloaded, fileSize);
                    }
                }
                outputStream.flush();
                SpUtil.setString("apkName", apkName);
                if (downloadStatusListener != null) {
                    downloadStatusListener.complete();
                }
            } catch (IOException e) {
                if (downloadStatusListener != null) {
                    downloadStatusListener.writeLocalError();
                }
                isDownloading = false;
                return false;
            } finally {
                if (inputStream != null) {
                    inputStream.close();
                }
                if (outputStream != null) {
                    outputStream.close();
                }

            }
        } catch (IOException e) {
            if (downloadStatusListener != null) {
                downloadStatusListener.writeLocalError();
            }
            isDownloading = false;
            return false;
        }
        return true;
    }

}
